﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DAL;
using System.Text;
using Newtonsoft.Json;

namespace PeisongWeb.admin
{
    public partial class buyerFixedPricePeriodEdit : adminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (hasPermission("CJ", 2))
                {
                    drp_buyerBind();
                    ext_startTime.MinDate = DateTime.Now.AddDays(2);
                    ext_endTime.MinDate = DateTime.Now.AddDays(2);
                    ext_startTime.SelectedDate = DateTime.Now.AddDays(2);
                    ext_endTime.SelectedDate = ext_startTime.SelectedDate.AddDays(7);
                }
                else
                {
                    Library.Script.ClientMsgUrl("没有权限！", "index.aspx");
                    return;
                }
            }
        }

        #region Part 1
        /// <summary>
        /// 绑定开通固定价格的采购商
        /// </summary>
        private void drp_buyerBind()
        {
            DataTable dt = logic.company.listWithWeeklyPrice();
            drp_buyer.DataSource = dt;
            drp_buyer.DataBind();
            drp_buyer.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));
        }

        protected void drp_company_SelectedIndexChanged(object sender, EventArgs e)
        {
            hd_proScope.Value = "";
            if (drp_buyer.SelectedValue.Trim() != "")
            {
                DataSet ds = logic.company.select("companyid=" + drp_buyer.SelectedValue.Trim(), "companyid", 1, 1);
                DataRow dr = ds.Tables[1].Rows[0];
                lbl_contact.Text = dr["contact"].ToString();
                lbl_Address.Text = dr["area"].ToString() + dr["address"].ToString();
                lbl_contactMobile.Text = dr["mobile"].ToString();
                if (dr["Phone"].ToString() != "" && dr["Phone"].ToString() != dr["mobile"].ToString())
                {
                    lbl_contactPhone.Text = "(" + dr["Phone"].ToString() + ")";
                }
                else
                {
                    lbl_contactPhone.Text = "";
                }
                DataRow drL = logic.buyerFixedPricePeriod.getLastperiodBybuyerid(Convert.ToInt32(drp_buyer.SelectedValue));
                ext_startTime.SelectedDate = Convert.ToDateTime(drL["endTime"]).AddDays(1);
            }
            else
            {
                lbl_contact.Text = "请选择公司";
                lbl_Address.Text = "请选择公司";
                lbl_contactMobile.Text = "请选择公司";
                lbl_contactPhone.Text = "";
            }
        }
        protected void lbn_AddProduct_Click(object sender, EventArgs e)
        {
            categoryRootBind();
            categorySubBind();
            rptProBind();
            win_product.Show();
        }

        /// <summary>
        /// 保存固定价格范围以及所需购买的商品信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Save_Click(object sender, EventArgs e)
        {
            // 日志记录
            log4net.ILog logger = log4net.LogManager.GetLogger("ApplicationFileAppender");//读取log4net的配置文件
            logger.Info("采购商固定价格商品信息:" + hd_proScope.Value);

            // 采购固定价格商品细目
            List<BuyerFixedPricePeriodItemEntity> bfpItems = JsonConvert.DeserializeObject<List<BuyerFixedPricePeriodItemEntity>>(hd_proScope.Value);

            if (bfpItems.Count > 0)
            {
                int buyerId = Convert.ToInt32(drp_buyer.SelectedValue);
                BuyerFixedPricePeriodEntity bfpEntity = new BuyerFixedPricePeriodEntity();
                bfpEntity.Buyerid = buyerId;
                bfpEntity.StartTime = ext_startTime.SelectedDate;
                bfpEntity.EndTime = ext_endTime.SelectedDate;
                bfpEntity.CreateAdminid = logic.sysAdmin.AdminID;
                int fpId = logic.buyerFixedPricePeriod.insert(bfpEntity);
                foreach (BuyerFixedPricePeriodItemEntity item in bfpItems)
                {
                    item.Fpid = fpId;
                    item.AdminId = logic.sysAdmin.AdminID;
                    logic.buyerFixedPricePeriodItem.insert(item);
                }
                Library.Script.ClientMsgUrl("固定价格保存成功!", "buyerFixedPricePeriodList.aspx");
            }
            else
            {
                Library.Script.ClientMsg("固定价格数据无效！");
                return;
            }
        }
        #endregion

        #region Part 2
        void rptProBind()
        {
            StringBuilder where = new StringBuilder();
            where.Append("isSale=1");

            if (ddl_CategorySub.SelectedValue != "")
                where.AppendFormat("and categoryId={0}", ddl_CategorySub.SelectedValue);
            if (txt_ProductNo.Text.Trim() != "")
                where.AppendFormat(" and productNo like '%{0}%'", txt_ProductNo.Text.Trim());
            if (txt_ProductName.Text.Trim() != "")
                where.AppendFormat(" and [Name] like '%{0}%'", txt_ProductName.Text.Trim());
            DataSet ds = logic.sellerRange.snnightOrderOptimize(where.ToString(), "productId", AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
            AspNetPager2.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            ViewState["seller"] = ds.Tables[2];
            rpt_Products.DataSource = ds.Tables[1];
            rpt_Products.DataBind();

        }
        protected void lbn_search_Click(object sender, EventArgs e)
        {
            AspNetPager2.CurrentPageIndex = 1;
            rptProBind();
        }

        protected void rpt_Products_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                DropDownList ddl = e.Item.FindControl("ddl") as DropDownList;
                DataRowView dv = e.Item.DataItem as DataRowView;

                DataTable dt = ViewState["seller"] as DataTable;
                DataView view = new DataView(dt);
                view.RowFilter = string.Format("productId={0}", dv["productId"]);
                view.Sort = "coi DESC";

                ddl.DataSource = view;
                ddl.DataBind();
            }
        }

        protected void AspNetPager2_PageChanged(object sender, EventArgs e)
        {
            rptProBind();
        }

        void categoryRootBind()
        {
            if (drp_buyer.SelectedValue != "")
            {
                int companyId = Convert.ToInt32(drp_buyer.SelectedValue);
                ddl_CategoryRoot.DataSource = logic.category.getByParent(0);
                ddl_CategoryRoot.DataBind();
                ddl_CategoryRoot.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));
            }
            else
            {
                ddl_CategoryRoot.Items.Clear();
            }
        }

        void categorySubBind()
        {
            //当大类不等于空的时候，就绑定小类
            if (ddl_CategoryRoot.SelectedValue != "")
            {
                DataTable dt = logic.category.getByParent(Convert.ToInt32(ddl_CategoryRoot.SelectedValue));
                ddl_CategorySub.DataSource = dt;
                ddl_CategorySub.DataBind();
            }
            else
            {
                ddl_CategorySub.Items.Clear();
            }
        }

        protected void ddl_CategoryRoot_SelectedIndexChanged(object sender, EventArgs e)
        {
            categorySubBind();
            AspNetPager2.CurrentPageIndex = 1;
            rptProBind();
        }

        protected void ddl_CategorySub_SelectedIndexChanged(object sender, EventArgs e)
        {
            AspNetPager2.CurrentPageIndex = 1;
            rptProBind();
        }

        #endregion
    }
}
